#!/bin/bash

# 书海拾贝状态检查脚本

PID_FILE="/home/bookocean/app.pid"
LOG_FILE="/home/bookocean/logs/app.log"

# 颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}📊 书海拾贝应用状态${NC}"
echo "================================="

# 检查PID文件
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p $PID > /dev/null 2>&1; then
        echo -e "状态: ${GREEN}✅ 运行中${NC}"
        echo "PID: $PID"
        echo "端口: 8082"
        echo "访问地址: https://bookocean.space/bookOcean/"
        
        # 显示进程信息
        echo ""
        echo "进程信息:"
        ps -p $PID -o pid,ppid,pcpu,pmem,etime,cmd --no-headers
        
        # 检查端口是否监听
        echo ""
        if netstat -tln 2>/dev/null | grep -q ":8082 "; then
            echo -e "端口状态: ${GREEN}✅ 8082端口正在监听${NC}"
        else
            echo -e "端口状态: ${YELLOW}⚠️  8082端口未监听${NC}"
        fi
        
        # 检查API是否可访问
        echo ""
        if curl -f -s --connect-timeout 5 "http://localhost:8082/actuator/health" > /dev/null 2>&1; then
            echo -e "健康检查: ${GREEN}✅ API响应正常${NC}"
        else
            echo -e "健康检查: ${YELLOW}⚠️  API无响应${NC}"
        fi
        
    else
        echo -e "状态: ${RED}❌ 未运行 (PID文件存在但进程不存在)${NC}"
        echo "清理PID文件..."
        rm -f "$PID_FILE"
    fi
else
    echo -e "状态: ${RED}❌ 未运行${NC}"
    
    # 检查是否有孤儿进程
    ORPHAN_PIDS=$(ps aux | grep "book-ocean-1.0.0.jar" | grep -v grep | awk '{print $2}')
    if [ -n "$ORPHAN_PIDS" ]; then
        echo -e "发现孤儿进程: ${YELLOW}$ORPHAN_PIDS${NC}"
    fi
fi

# 显示最近的日志
echo ""
echo "================================="
echo -e "${BLUE}📝 最近日志 (最后10行):${NC}"
if [ -f "$LOG_FILE" ]; then
    tail -n 10 "$LOG_FILE"
else
    echo "日志文件不存在: $LOG_FILE"
fi

echo ""
echo "================================="
echo "管理命令:"
echo "启动: ./start-bookocean.sh"
echo "停止: ./stop-bookocean.sh"
echo "状态: ./status-bookocean.sh"
